<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="维修状态" label-width="70px">
          <el-select
            v-model="searchParam.orderStatus"
            placeholder="请选择维修状态"
            clearable
            filterable
          >
            <el-option
              v-for="item in useDictionary('RepairOrderStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户">
          <el-select
            v-model="searchParam.projectId"
            placeholder="请选择客户"
            clearable
            filterable
            @change="changeProjectId"
          >
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.partnerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模具" label-width="40px">
          <el-select
            v-model="searchParam.assetCode"
            placeholder="请输入模具编号"
            clearable
            filterable
            :filter-method="mouldCustomFilter"
          >
            <el-option
              v-for="item in mouldFilteredOptions"
              :key="`${item.assetCode}`"
              :label="`${item.assetName}`"
              :value="`${item.assetCode}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维修类型">
          <el-select
            v-model="searchParam.planRepairType"
            placeholder="请选择维修类型"
            clearable
            filterable
          >
            <el-option
              v-for="item in useDictionary('EamRepairType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!--        <el-form-item label="工单编号">-->
        <!--          <el-input-->
        <!--            v-model="searchParam.orderNo"-->
        <!--            placeholder="请输入工单编号"-->
        <!--            clearable-->
        <!--            @keyup.enter="search"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="维修时间" label-width="70px">
          <el-date-picker
            v-model="searchParam.repairStartTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getRepairStartTime"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetHandle"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <!--        <el-table-column-->
        <!--          label="维修计划"-->
        <!--          prop="planName"-->
        <!--          min-width="160"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <el-table-column
          label="工单编号"
          prop="orderNo"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="维修状态"
          prop="orderStatus"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{ useDictionary("RepairOrderStatus", scope.row.orderStatus) }}
            <!--            {{ scope.row.orderStatus }}-->
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="维修班组"
          prop="executeTeamName"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        /> -->
        <el-table-column
          label="维修参与人"
          prop="maintainUser"
          min-width="120"
          show-overflow-tooltip
          sortable
          align="center"
        >
          <!-- <template #default="scope">
            {{
              scope.row.repairOrderPersons
                ?.map((item) => item.personName)
                .join(",")
            }}
          </template> -->
        </el-table-column>
        <el-table-column
          label="主修人员"
          prop="repairUserName"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          label="计划维修时间"
          prop="planStartTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{
              scope.row.planStartTime
                ? dayjs(scope.row.planStartTime).format("YYYY-MM-DD")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="模具编号"
          prop="assetCode"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="模具名称"
          prop="assetName"
          min-width="150"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="位置"
          prop="locationName"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="维修类型"
          prop="planRepairType"
          min-width="120"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            {{ useDictionary("EamRepairType", scope.row.planRepairType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="维修内容"
          prop="repairContent"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="维修开始时间"
          prop="repairStartTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          label="维修结束时间"
          prop="repairEndTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          label="维修用时"
          prop="repairUseTime"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          label="维修情况说明"
          prop="repairSituation"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="其他问题"
          prop="otherProblem"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <moldplanrepairorder-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import dayjs from "dayjs";
import { uniqBy } from "lodash-es";
import { filterOrder } from "@/utils/commonHooks";
import _ from "lodash-es";
defineOptions({
  name: "EAMMOLDPLANREPAIRORDER",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/mouldplanrepairorder/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  orderNo: "",
  orderStatus: "",
  assetCode: "",
  assetKind: 3,
  executeTeamId: "",
  repairUserId: "",
  repairStartTimeSearch: [],
  repairStartTimeEnd: "",
  repairStartTimeStart: "",
};

const deleteParam = {
  api: "/eam/mouldplanrepairorder/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}

// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
onMounted(() => {
  getTableList();
  getMouldList();
  getCustomerList();
  getPlanList();
  // getExecuteTeamList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamplanrepairorder/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开计划修工单表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改计划修工单";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增计划修工单";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开计划修工单表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "计划修工单详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getRepairStartTime(data: any) {
  if (data) {
    searchParam.value.repairStartTimeStart = data[0];
    searchParam.value.repairStartTimeEnd = data[1];
  } else {
    searchParam.value.repairStartTimeStart = "";
    searchParam.value.repairStartTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/eamplanrepairorder/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

const planList = ref([]);

const getPlanList = async () => {
  const { data } = await request({
    url: "/eam/mouldrepairplan/getList",
    method: "post",
    data: { planStatus: [1, 2] },
  });
  planList.value = data;
};
const executeTeamList = ref([]);

const getExecuteTeamList = async () => {
  const { data } = await request({
    url: "/eam/eamTeam/getList",
    method: "post",
    data: {},
  });
  executeTeamList.value = data;
};

const executeTeamMemberList = ref([]);

const changeTeam = async (teamId) => {
  const { data } = await request({
    url: "/eam/eamteammember/getList",
    method: "post",
    data: { teamIdList: [teamId] },
  });
  executeTeamMemberList.value = data ? uniqBy(data, "memberId") : [];
};

const mouldList: any = ref([]);
const getMouldList = async () => {
  // 获取内容树
  await request({
    url: "/eam/mouldAssetInfo/getList",
    method: "POST",
    data: {},
  }).then((res) => {
    mouldList.value = res.data;
    mouldFilteredOptions.value = res.data;
  });
};
const mouldFilteredOptions = ref([]);
// 使用 debounce 包装过滤方法
const mouldCustomFilter = _.debounce((query: any) => {
  if (!query) {
    mouldFilteredOptions.value = [...mouldList.value];
    return;
  }
  mouldFilteredOptions.value = mouldList.value.filter((option: any) =>
    option.assetName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);

// 获取客户
const customerList: any = ref([]);
const getCustomerList = async () => {
  // 获取内容树
  await request({
    url: "/mdm/mdmpartner/getPoList",
    method: "POST",
    data: {},
  }).then((res) => {
    customerList.value = res.data;
  });
};
const changeProjectId = async () => {
  await request({
    url: "/eam/mouldAssetInfo/getList",
    method: "POST",
    data: { projectId: searchParam.value.projectId },
  }).then((res) => {
    mouldList.value = res.data;
    mouldFilteredOptions.value = res.data;
    if (searchParam.value.assetCode) {
      if (
        mouldList.value.find(
          (item: any) => item.assetCode == searchParam.value.assetCode
        )
      ) {
      } else {
        searchParam.value.assetCode = "";
      }
    }
  });
};
const resetHandle = () => {
  reset();
  executeTeamMemberList.value = [];
};
</script>
